<template>
    <div class="listen">
        <TopNav :items="navItems" :initialActiveId="navActive" @update:activeItem="handleNavClick" />
        <div v-if="!loading" class="container">
            <div class="sidebar" ref="sidebarRef">
                <button
                    v-for="(item, index) in items"
                    :key="index"
                    :class="['nav-button', { active: activeIndex === index }]"
                    @click="scrollToSection(index)"
                >
                    {{ item.name }}
                </button>
            </div>
            <div class="content" ref="contentRef" @scroll="handleScroll">
                <div
                    v-for="(item, index) in items"
                    :key="index"
                    class="content-section"
                    :data-index="index"
                    ref="sections"
                >
                    <div v-for="(item1, index1) in item.list" :key="index1" class="content-box">
                        <div class="tit">{{ item1.typeName }}</div>
                        <div class="list-box">
                            <div v-for="(item2, index2) in item1.practiceList" :key="index2" class="list-item">
                                <div class="margin-20" @click="startExam(item2)">
                                    <div>
                                        <div class="item-left">
                                            <div>{{ item2.examName }}&nbsp;</div>
                                            <div v-if="navActive !==3 && item2.knowledgeType" class="blue-icon">{{ item2.knowledgeType }}</div>
                                        </div>
                                        <div class="subTitle" v-html="item2.title"></div>
                                    </div>
                                    <div v-if="item2.practiceStatus == 2" class="item-right">
                                        正确率：<span>{{ item2.rightTopicCount }}</span>/{{ item2.allTopicCount }}
                                    </div>
                                </div>
                                <div v-if="item2.latestPractice" class="red-icon">上次练习</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div v-if="loading" class="loading-box">
            <van-loading color="#1989fa" />
        </div>
        <!--弹窗-->
        <van-popup v-model:show="showPopup" round :style="{ padding: '20px', width: '300px' }">
            <div class="popup-blank">
                <div class="title">上次答题中断，是否继续作答？</div>
                <div class="btn-list">
                    <div class="btn popup-cancel" @click="handleCancel">继续作答</div>
                    <div class="btn popup-ok" @click="handleOk">重新作答</div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup>
import TopNav from '../components/TopNav.vue'
import { ref, reactive, onActivated, onMounted } from 'vue'
import { apiGetReadClass, apiGetReadTestList } from '@/api/exam.js'
import { showToast } from 'vant'
import { apiReDoExam } from '@/api/exam'
import { useRouter } from 'vue-router'

// 示例数据，用于导航项
const navItems = ref([
    { id: 1, label: '顺序' },
    { id: 2, label: '题型' },
    { id: 3, label: '场景' }
])
const navActive = ref(1)
const itemVal = ref('')
const contentRefScrollTop = ref(0)

// 处理来自 TopNav 的点击事件
function handleNavClick(id) {
    console.log('导航项被点击:', id)
    navActive.value = id
    items.value = []
    getClassList(id)
}

const items = ref(null)

const router = useRouter()
const activeIndex = ref(0)
const contentRef = ref(null)
const sections = ref([])
const sidebarRef = ref(null)

const showPopup = ref(false)
const loading = ref(false)
const state = reactive({
    rows: [],
    testList: [],
    currentTest: {
        examId: null,
        recordId: null
    },
    activeTab: Number(0)
})

// 滚动到选定的部分
const scrollToSection = (index) => {
    activeIndex.value = index
    sections.value[index].scrollIntoView({ behavior: 'auto' })
}

// 处理滚动事件并更新激活按钮
const handleScroll = () => {
    const scrollTop = contentRef.value.scrollTop + contentRef.value.offsetTop
    contentRefScrollTop.value = contentRef.value.scrollTop
    let index = 0

    sections.value.forEach((section, i) => {
        const offsetTop = section.offsetTop
        const height = section.offsetHeight

        if (Math.ceil(scrollTop) >= offsetTop && scrollTop < offsetTop + height) {
            index = i
        }
    })
    activeIndex.value = index

    // 确保激活的按钮在视图中
    const sidebar = sidebarRef.value
    const activeButton = sidebar.querySelector('.nav-button.active')
    if (activeButton) {
        const sidebarScrollTop = sidebar.scrollTop
        const sidebarHeight = sidebar.offsetHeight
        const buttonTop = activeButton.offsetTop
        const buttonHeight = activeButton.offsetHeight

        // 确保活跃的按钮在视图中
        if (buttonTop < sidebarScrollTop) {
            sidebar.scrollTop = buttonTop
        } else if (buttonTop + buttonHeight > sidebarScrollTop + sidebarHeight) {
            sidebar.scrollTop = buttonTop + buttonHeight - sidebarHeight
        }
    }
}

// 组件挂载时初始化 sections 数组
onMounted(() => {
    sections.value = Array.from(contentRef.value.querySelectorAll('.content-section'))
    console.log(sections.value)
    const queryParams = new URLSearchParams(window.location.search)
    const type = Number(queryParams.get('readType'))
    handleNavClick(type)
})
onActivated(() => {
    if (itemVal.value) {
        contentRef.value.scrollTop = contentRefScrollTop.value
        updateList(itemVal.value, navActive.value)
    }
})

async function updateList(item, type) {
    const testList = await apiGetReadTestList({
        searchStr: item,
        type: type
    })
    for (let i = 0; i < items.value.length; i++) {
        // 检查 name 是否为 '周一'
        if (items.value[i].name === item) {
            // 替换 list 数据
            items.value[i].list = testList
            // 中止循环
            break
        }
    }
}

/**
 * 获取头部分类列表
 * @param  type number 1 顺序模式 2 分类
 */
async function getClassList(type) {
    const list = []
    loading.value = true
    try {
        const classList = await apiGetReadClass(type) // 等待获取初始的 class list
        for (const item of classList) {
            const testList = await apiGetReadTestList({
                searchStr: item,
                type: type
            })

            list.push({
                name: item,
                list: testList
            }) // 将 test list 添加到结果列表中
        }
    } catch (error) {
        loading.value = false
        console.error('Error fetching data:', error)
    }
    console.log(list)
    loading.value = false
    activeIndex.value = 0
    items.value = list
}

/**
 * 跳转到做题页面
 * @param item Object
 */
function startExam(item) {
    itemVal.value = items.value[activeIndex.value].name
    state.currentTest = item
    if (item.practiceStatus === 1) {
        // 弹出提示框
        showPopup.value = true
    } else {
        getExamData({
            examId: item.examId
        })
    }
}

function getExamData(data) {
    const toast = showToast({
        type: 'loading',
        message: '加载中...',
        forbidClick: true,
        duration: 0
    })
    apiReDoExam(data).then((res) => {
        toast.close()
        router.push({
            name: 'exam',
            query: {
                id: res.recordId
            }
        })
    })
}

// 弹窗取消按钮
function handleCancel() {
    showPopup.value = false
    getExamData({
        examId: state.currentTest.examId,
        recordId: state.currentTest.recordId,
        reAnswerFlag: false
    })
}

// 弹窗确定按钮
function handleOk() {
    showPopup.value = false
    getExamData({
        examId: state.currentTest.examId,
        recordId: state.currentTest.recordId,
        reAnswerFlag: true
    })
}

</script>

<style lang="scss" scoped>
.listen {
    height: 100vh;
    background: #F6F8FC;
}

.container {
    display: flex;
    height: calc(100vh - 3.0625rem);
    box-sizing: border-box;
}
.loading-box {
    width: 100%;
    height: calc(100vh - 3.0625rem);
    display: flex;
    align-items: center;
    justify-content: center;
}

.sidebar {
    width: 5.1875rem;
    background: #fff;
    overflow-y: auto;
    position: relative;
    border-radius: 0 10px 0 0;
    &::-webkit-scrollbar {
        display: none;
    }
}

.nav-button {
    display: block;
    width: 100%;
    height: 3.125rem;
    border: none;
    background: #fff;
    cursor: pointer;
    text-align: left;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: .875rem;
    color: #999999;
    text-align: center;
    padding: 0;
    box-sizing: border-box;
}

.nav-button.active {
    background: linear-gradient(180deg, #6B9EF8, #2E55E5);
    font-weight: 600;
    color: #FFFFFF;
}

.content {
    flex: 1;
    overflow-y: auto;
    /* padding: 10px; */
    /* background: #fff; */
}

.content-section {
    padding: 1.15rem .625rem 0;
    // border-bottom: 1px solid #ddd;
    box-sizing: border-box;
    &:last-child {
        min-height: 100%;
    }
    .content-box {
        &:first-child .tit {
            margin-top: 0 !important;
        }
    }
}
.content-section .tit {
    font-family: PingFang SC;
    font-weight: 600;
    font-size: .875rem;
    color: #333333;
    margin-bottom: .9375rem;
    margin-top: .9375rem;

}
.content-section .list-box {
    background: #FFFFFF;
    border-radius: 10rpx;
    .list-item {
        height: 3.75rem;
        border-bottom: 1px solid #f5f5f5;
        position: relative;
        .red-icon{
            position: absolute;
            top: 0;
            right: 0;
            // height: 1rem;
            background: rgba(253,69,61,0.1);
            border-radius: 0px 10px 0px 10px;
            text-align: center;
            font-family: PingFang SC;
            font-weight: 400;
            font-size: .6875rem;
            line-height: .6875rem;
            color: #FD453D;
            // line-height: 1rem;
            -webkit-text-size-adjust:none;
            padding: .3125rem .5rem;
        }
        &:last-child {
            border: 0;
        }
        .margin-20 {
            height: 3.75rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin: 0 .625rem;
            .item-right {
                // width: 5.625rem;
                font-family: PingFang SC;
                font-weight: 400;
                font-size: .6875rem;
                color: #333333;
                white-space: nowrap;
                span{
                    font-weight: bold;
                    font-size: .875rem;
                }
            }
            .item-left {
                // width: calc(100% - 5.625rem);
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                font-family: PingFang SC;
                font-weight: 400;
                font-size: .875rem;
                color: #333333;
                .blue-icon {
                    background: #99BCFF;
                    border-radius: .25rem;
                    font-family: PingFang SC;
                    font-weight: 400;
                    font-size: .625rem;
                    line-height: .625rem;
                    color: #FFFFFF;
                    padding: .3125rem;
                }
            }
            .subTitle {
                width: 10rem;
                font-family: PingFang SC;
                font-weight: 400 !important;
                font-size: .75rem;
                color: #999999;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
                b{
                    font-weight: 400 !important;
                }
            }
        }
    }
}

/* 弹窗 */
.popup-blank {
    .title {
        color: #333333;
        font-size: 14px;
        line-height: 40px;
        text-align: center;
        font-weight: bold;
    }
    .btn-list {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30px;
        box-sizing: border-box;
        .btn {
            width: 80px;
            height: 30px;
            background: #f6f8fc;
            font-size: 12px;
            text-align: center;
            line-height: 30px;
            margin-top: 25px;
        }
        .popup-cancel {
            background: #8287FA;
            color: #fff;
        }
        .popup-ok {
            border: 1px solid #8287FA;
            color: #8287FA;
            background-color: #fff;
        }
    }
}
</style>
